<template>
  <div class="user-management-container">
    <div class="header">
      <h1>用户管理</h1>
    </div>
    
    <!-- 搜索和筛选区域 -->
    <div class="filter-section">
      <div class="filter-row">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索用户名、邮箱、姓名"
          prefix-icon="Search"
          style="width: 300px; margin-right: 16px"
          @keyup.enter="fetchUsers"
        />
        
        <el-select
          v-model="roleFilter"
          placeholder="用户角色"
          style="width: 150px; margin-right: 16px"
          @change="fetchUsers"
        >
          <el-option label="全部" value="" />
          <el-option label="普通用户" value="user" />
          <el-option label="管理员" value="admin" />
        </el-select>
        
        <el-select
          v-model="statusFilter"
          placeholder="用户状态"
          style="width: 150px; margin-right: 16px"
          @change="fetchUsers"
        >
          <el-option label="全部" value="" />
          <el-option label="启用" value="true" />
          <el-option label="禁用" value="false" />
        </el-select>
        
        <el-button type="primary" @click="fetchUsers" style="margin-left: 16px">
          搜索
        </el-button>
        
        <el-button @click="resetFilters" style="margin-left: 8px">
          重置
        </el-button>
      </div>
    </div>
    
    <!-- 用户表格 -->
    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="users"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="用户ID" width="100" />
        <el-table-column prop="username" label="用户名" width="150" />
        <el-table-column prop="email" label="邮箱" width="200" />
        <el-table-column prop="firstName" label="姓名">
          <template #default="scope">{{ scope.row.firstName }} {{ scope.row.lastName }}</template>
        </el-table-column>
        <el-table-column prop="role" label="角色" width="100">
          <template #default="scope">
            <el-select
              v-model="usersRoleMap[scope.row.id]"
              placeholder="角色"
              @change="handleRoleChange(scope.row.id, $event)"
              size="small"
            >
              <el-option label="普通用户" value="user" />
              <el-option label="管理员" value="admin" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="isActive" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="usersStatusMap[scope.row.id]"
              @change="handleStatusChange(scope.row.id, $event)"
              :disabled="isCurrentUser(scope.row.id)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="注册时间" width="180">
          <template #default="scope">{{ formatDate(scope.row.createdAt) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="text" size="small" @click="viewUserDetail(scope.row.id)">
              详情
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="showDeleteConfirm(scope.row)"
              :disabled="isCurrentUser(scope.row.id)"
              danger
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <!-- 分页 -->
    <div class="pagination">
      <div class="batch-actions" v-if="selectedUsers.length > 0">
        <el-button @click="batchDeleteUsers" danger>
          批量删除 ({{ selectedUsers.length }})
        </el-button>
      </div>
      
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    
    <!-- 用户详情弹窗 -->
    <el-dialog
      v-model="userDetailDialogVisible"
      title="用户详情"
      width="700px"
    >
      <div v-if="currentUser" class="user-detail-content">
        <div class="user-info">
          <h3>基本信息</h3>
          <div class="info-grid">
            <div class="info-item">
              <span class="info-label">用户ID:</span>
              <span class="info-value">{{ currentUser.id }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">用户名:</span>
              <span class="info-value">{{ currentUser.username }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">邮箱:</span>
              <span class="info-value">{{ currentUser.email }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">姓名:</span>
              <span class="info-value">{{ currentUser.firstName }} {{ currentUser.lastName }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">角色:</span>
              <span class="info-value">{{ currentUser.role === 'admin' ? '管理员' : '普通用户' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">状态:</span>
              <span class="info-value">{{ currentUser.isActive ? '启用' : '禁用' }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">注册时间:</span>
              <span class="info-value">{{ formatDate(currentUser.createdAt) }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">上次登录:</span>
              <span class="info-value">{{ currentUser.lastLogin ? formatDate(currentUser.lastLogin) : '未登录过' }}</span>
            </div>
          </div>
        </div>
        
        <div class="user-orders">
          <h3>最近订单</h3>
          <el-table v-if="currentUser.orders && currentUser.orders.length > 0" :data="currentUser.orders" style="width: 100%">
            <el-table-column prop="id" label="订单号" width="120" />
            <el-table-column prop="totalAmount" label="订单金额" width="100">
              <template #default="scope">¥{{ Number(scope.row.totalAmount).toFixed(2) }}</template>
            </el-table-column>
            <el-table-column prop="status" label="订单状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdAt" label="下单时间">
              <template #default="scope">{{ formatDate(scope.row.createdAt) }}</template>
            </el-table-column>
          </el-table>
          <div v-else class="no-orders">暂无订单记录</div>
        </div>
        
        <div class="user-stats" v-if="userStats">
          <h3>用户统计</h3>
          <div class="stats-grid">
            <div class="stat-item">
              <span class="stat-label">总订单数:</span>
              <span class="stat-value">{{ userStats.totalOrders }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">消费总额:</span>
              <span class="stat-value">¥{{ Number(userStats.totalSpent).toFixed(2) }}</span>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="userDetailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';
import { Search } from '@element-plus/icons-vue';
import axiosInstance from '../../api/axiosInstance';

// 用户接口
interface User {
  id: number;
  username: string;
  email: string;
  firstName: string;
  lastName: string;
  role: 'user' | 'admin';
  isActive: boolean;
  createdAt: string;
  updatedAt: string;
  lastLogin?: string;
  phone?: string;
  orders?: UserOrder[];
}

// 用户订单接口
interface UserOrder {
  id: number;
  orderNumber: string;
  status: string;
  totalAmount: string;
  createdAt: string;
}

// 用户统计接口
interface UserStats {
  totalOrders: number;
  totalSpent: string;
}

interface Pagination {
  currentPage: number;
  pageSize: number;
  total: number;
}

const router = useRouter();

// 用户数据
const users = ref<User[]>([]);
const loading = ref(false);
const pagination = reactive<Pagination>({
  currentPage: 1,
  pageSize: 20,
  total: 0
});

// 筛选条件
const searchKeyword = ref('');
const roleFilter = ref('');
const statusFilter = ref('');

// 选择的用户
const selectedUsers = ref<User[]>([]);

// 用户详情相关
const userDetailDialogVisible = ref(false);
const currentUser = ref<User | null>(null);
const userStats = ref<UserStats | null>(null);

// 用户状态和角色映射（用于即时更新）
const usersStatusMap = ref<Record<number, boolean>>({});
const usersRoleMap = ref<Record<number, string>>({});

// 当前登录用户ID（从localStorage中获取）
const currentUserId = computed(() => {
  const userInfo = localStorage.getItem('userInfo');
  if (userInfo) {
    try {
      const user = JSON.parse(userInfo);
      return user.id;
    } catch (e) {
      return null;
    }
  }
  return null;
});

// 获取用户列表
const fetchUsers = async () => {
  loading.value = true;
  
  try {
    const params: any = {
      page: pagination.currentPage,
      limit: pagination.pageSize
    };
    
    // 添加筛选条件
    if (searchKeyword.value.trim()) {
      params.search = searchKeyword.value.trim();
    }
    
    if (roleFilter.value) {
      params.role = roleFilter.value;
    }
    
    if (statusFilter.value !== '') {
      params.isActive = statusFilter.value === 'true';
    }
    
    const response = await axiosInstance.get('/admin/users', { params });
    users.value = response.data.data.users;
    pagination.total = response.data.data.pagination.total;
    
    // 初始化状态和角色映射
    users.value.forEach(user => {
      usersStatusMap.value[user.id] = user.isActive;
      usersRoleMap.value[user.id] = user.role;
    });
  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 重置筛选条件
const resetFilters = () => {
  searchKeyword.value = '';
  roleFilter.value = '';
  statusFilter.value = '';
  pagination.currentPage = 1;
  fetchUsers();
};

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  fetchUsers();
};

const handleCurrentChange = (current: number) => {
  pagination.currentPage = current;
  fetchUsers();
};

// 选择用户变化
const handleSelectionChange = (selection: User[]) => {
  selectedUsers.value = selection;
};

// 查看用户详情
const viewUserDetail = async (userId: number) => {
  try {
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '加载中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    
    const response = await axiosInstance.get(`/admin/users/${userId}`);
    currentUser.value = response.data.data.user;
    userStats.value = response.data.data.stats;
    userDetailDialogVisible.value = true;
  } catch (error) {
    console.error('获取用户详情失败:', error);
    ElMessage.error('获取用户详情失败，请重试');
  } finally {
    ElLoading.service().close();
  }
};

// 处理用户状态变化
const handleStatusChange = async (userId: number, isActive: boolean) => {
  try {
    await axiosInstance.patch(`/admin/users/${userId}/status`, { isActive });
    ElMessage.success('用户状态更新成功');
  } catch (error) {
    console.error('更新用户状态失败:', error);
    // 恢复原来的状态
    usersStatusMap.value[userId] = !isActive;
    ElMessage.error('更新用户状态失败，请重试');
  }
};

// 处理用户角色变化
const handleRoleChange = async (userId: number, role: string) => {
  try {
    await axiosInstance.patch(`/admin/users/${userId}/status`, { role });
    ElMessage.success('用户角色更新成功');
  } catch (error) {
    console.error('更新用户角色失败:', error);
    // 恢复原来的角色
    users.value.forEach(user => {
      if (user.id === userId) {
        usersRoleMap.value[userId] = user.role;
      }
    });
    ElMessage.error('更新用户角色失败，请重试');
  }
};

// 显示删除确认对话框
const showDeleteConfirm = (user: User) => {
  ElMessageBox.confirm(
    `确定要删除用户 "${user.username}" 吗？此操作不可撤销。`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      await deleteUser(user.id);
    })
    .catch(() => {
      // 用户取消删除
    });
};

// 删除用户
const deleteUser = async (userId: number) => {
  try {
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '删除中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });
    
    await axiosInstance.delete(`/admin/users/${userId}`);
    ElMessage.success('用户删除成功');
    fetchUsers(); // 刷新用户列表
  } catch (error) {
    console.error('删除用户失败:', error);
    ElMessage.error('删除用户失败，请重试');
  } finally {
    ElLoading.service().close();
  }
};

// 批量删除用户
const batchDeleteUsers = () => {
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedUsers.value.length} 个用户吗？此操作不可撤销。`,
    '批量删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        const loadingInstance = ElLoading.service({
          lock: true,
          text: '批量删除中...',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        
        // 依次删除用户（在实际项目中可以考虑使用批量API）
        for (const user of selectedUsers.value) {
          if (!isCurrentUser(user.id)) {
            await axiosInstance.delete(`/admin/users/${user.id}`);
          }
        }
        
        ElMessage.success(`成功删除 ${selectedUsers.value.length} 个用户`);
        selectedUsers.value = [];
        fetchUsers(); // 刷新用户列表
      } catch (error) {
        console.error('批量删除用户失败:', error);
        ElMessage.error('批量删除用户失败，请重试');
      } finally {
        ElLoading.service().close();
      }
    })
    .catch(() => {
      // 用户取消删除
    });
};

// 判断是否为当前用户
const isCurrentUser = (userId: number): boolean => {
  return userId === currentUserId.value;
};

// 获取订单状态对应的标签类型
const getStatusType = (status: string): string => {
  const typeMap: Record<string, string> = {
    'pending': 'warning',
    'paid': 'primary',
    'shipped': 'info',
    'delivered': 'success',
    'cancelled': 'danger'
  };
  
  return typeMap[status] || 'default';
};

// 获取订单状态显示文本
const getStatusText = (status: string): string => {
  const textMap: Record<string, string> = {
    'pending': '待支付',
    'paid': '已支付',
    'shipped': '已发货',
    'delivered': '已完成',
    'cancelled': '已取消'
  };
  
  return textMap[status] || status;
};

// 格式化日期
const formatDate = (dateString: string): string => {
  const date = new Date(dateString);
  return new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).format(date);
};

// 组件挂载时获取用户列表
onMounted(() => {
  fetchUsers();
});
</script>

<style scoped>
.user-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.header {
  margin-bottom: 24px;
}

.header h1 {
  font-size: 24px;
  font-weight: 600;
  margin: 0;
  color: #333;
}

.filter-section {
  background: #fff;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.filter-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.table-container {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination {
  background: #fff;
  padding: 16px;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.batch-actions {
  flex: 1;
}

.user-detail-content {
  max-height: 500px;
  overflow-y: auto;
}

.user-info {
  margin-bottom: 24px;
}

.user-info h3,
.user-orders h3,
.user-stats h3 {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 16px;
  color: #333;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.info-label {
  color: #606266;
  font-size: 14px;
}

.info-value {
  color: #303133;
  font-size: 14px;
  font-weight: 500;
}

.no-orders {
  text-align: center;
  padding: 20px;
  color: #909399;
  font-size: 14px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 8px;
}

.stat-label {
  display: block;
  color: #606266;
  font-size: 14px;
  margin-bottom: 8px;
}

.stat-value {
  display: block;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-management-container {
    padding: 12px;
  }
  
  .filter-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-row > * {
    width: 100% !important;
    margin-right: 0 !important;
    margin-left: 0 !important;
  }
  
  .pagination {
    padding: 12px;
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .batch-actions {
    text-align: center;
  }
  
  .el-pagination {
    justify-content: center;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
}
</style>